#include "TimedWidget.h"
#include "StyleLoader.h"
#include <QDebug>
#include <QFontDatabase>
#include <QMessageBox>
#include "log.h"

TimedWidget::TimedWidget(int nScreenWidth,int nScreenHeigth,QWidget *parent)
    : QWidget{parent}
    ,m_nScreenWidth(nScreenWidth)
    ,m_nScreenHeigth(nScreenHeigth)
{
    initData();
    
    // 从QSS文件加载样式
    QString style = StyleLoader::loadDarkTheme();
    if (!style.isEmpty()) {
        setStyleSheet(style);
    } else {
        qWarning() << "警告：样式文件加载失败！请检查 resource.qrc 配置。";
    }
    setupForm();
}

TimedWidget::~TimedWidget()
{
    // 保存数据
    saveData();

    // 删除指针的检查和释放
    if (cbTimerDuration) {
        delete cbTimerDuration;
        cbTimerDuration = nullptr;
    }

    if (sbHour) {
        delete sbHour;
        sbHour = nullptr;
    }

    if (sbMinute) {
        delete sbMinute;
        sbMinute = nullptr;
    }

    if (sbSecond) {
        delete sbSecond;
        sbSecond = nullptr;
    }

    if (rbCountdown) {
        delete rbCountdown;
        rbCountdown = nullptr;
    }

    if (rbCountup) {
        delete rbCountup;
        rbCountup = nullptr;
    }

    if (cbWarning1) {
        delete cbWarning1;
        cbWarning1 = nullptr;
    }

    if (sbWarning1Time) {
        delete sbWarning1Time;
        sbWarning1Time = nullptr;
    }

    if (cbWarning2) {
        delete cbWarning2;
        cbWarning2 = nullptr;
    }

    if (sbWarning2Time) {
        delete sbWarning2Time;
        sbWarning2Time = nullptr;
    }

    if (cbWarning3) {
        delete cbWarning3;
        cbWarning3 = nullptr;
    }

    if (sbWarning3Time) {
        delete sbWarning3Time;
        sbWarning3Time = nullptr;
    }

    if (cbContinuousWarning) {
        delete cbContinuousWarning;
        cbContinuousWarning = nullptr;
    }

    if (cbOvertime) {
        delete cbOvertime;
        cbOvertime = nullptr;
    }

    if (sbOvertimeDuration) {
        delete sbOvertimeDuration;
        sbOvertimeDuration = nullptr;
    }

    if (rbFormat59Sec) {
        delete rbFormat59Sec;
        rbFormat59Sec = nullptr;
    }

    if (rbFormat59MinSec) {
        delete rbFormat59MinSec;
        rbFormat59MinSec = nullptr;
    }

    if (rbFormat23HoursMinSec) {
        delete rbFormat23HoursMinSec;
        rbFormat23HoursMinSec = nullptr;
    }

    if (rbOvertimeCount) {
        delete rbOvertimeCount;
        rbOvertimeCount = nullptr;
    }

    if (rbStopCount) {
        delete rbStopCount;
        rbStopCount = nullptr;
    }

    if (rbLoopCount) {
        delete rbLoopCount;
        rbLoopCount = nullptr;
    }

    if (cbTransparent) {
        delete cbTransparent;
        cbTransparent = nullptr;
    }

    if (cbScreenBlack) {
        delete cbScreenBlack;
        cbScreenBlack = nullptr;
    }

    if (cbScreenWhite) {
        delete cbScreenWhite;
        cbScreenWhite = nullptr;
    }

    if (cbSmartCount) {
        delete cbSmartCount;
        cbSmartCount = nullptr;
    }

    if (cbCountSettings) {
        delete cbCountSettings;
        cbCountSettings = nullptr;
    }

    if (cbPauseCount) {
        delete cbPauseCount;
        cbPauseCount = nullptr;
    }

    if (cbChangeTime) {
        delete cbChangeTime;
        cbChangeTime = nullptr;
    }

    if (cbHideClock) {
        delete cbHideClock;
        cbHideClock = nullptr;
    }

    if (cbShowOnSecondaryScreen) {
        delete cbShowOnSecondaryScreen;
        cbShowOnSecondaryScreen = nullptr;
    }

    if (fontCombo) {
        delete fontCombo;
        fontCombo = nullptr;
    }

    if (fontSizeCombo) {
        delete fontSizeCombo;
        fontSizeCombo = nullptr;
    }

    if (colorCombo) {
        delete colorCombo;
        colorCombo = nullptr;
    }

    if (cbTransparentBackground) {
        delete cbTransparentBackground;
        cbTransparentBackground = nullptr;
    }

    if (backgroundPath) {
        delete backgroundPath;
        backgroundPath = nullptr;
    }

    if (radiusSpinBox) {
        delete radiusSpinBox;
        radiusSpinBox = nullptr;
    }

    if (btnSpecialCount) {
        delete btnSpecialCount;
        btnSpecialCount = nullptr;
    }

    if (btnHelp) {
        delete btnHelp;
        btnHelp = nullptr;
    }

    if (btnApply) {
        delete btnApply;
        btnApply = nullptr;
    }

    if (btnClose) {
        delete btnClose;
        btnClose = nullptr;
    }
}

void TimedWidget::setFormSize(int nScreenWidth, int nScreenHeigth)
{
    m_nScreenWidth = nScreenWidth;
    m_nScreenHeigth = nScreenHeigth;
}
#include <QScrollArea>

void TimedWidget::setupForm()
{
    const int width_size = 50;
    const int width_size_SpinBox = 200;
    // 创建主布局
    QVBoxLayout *mainLayout = new QVBoxLayout(this);

    QGroupBox *headGroup = new QGroupBox(this); // 设置父对象为 this
    // 移除固定高度限制，让内容自然撑开（配合SettingWidget的滚动区域）
    QVBoxLayout* headLayout = new QVBoxLayout(headGroup); // 设置父对象为 headGroup，自动成为headGroup的布局

    QHBoxLayout *head1 = new QHBoxLayout();  // 不指定父对象，通过addLayout添加
    cbTimerDuration = new QCheckBox("计时时长", headGroup);

    sbHour = new QSpinBox(headGroup);
    // 连接 QSpinBox 的 valueChanged 信号到槽函数
    connect(sbHour, SIGNAL(valueChanged(int)), this, SLOT(updateLabel(int)));
    sbHour->setMaximum(23);
    sbHour->setMinimum(0);
    sbMinute = new QSpinBox(headGroup);
    connect(sbMinute, SIGNAL(valueChanged(int)), this, SLOT(updateLabel(int)));
    sbMinute->setMaximum(59);
    sbMinute->setMinimum(0);
    sbSecond = new QSpinBox(headGroup);
    connect(sbSecond, SIGNAL(valueChanged(int)), this, SLOT(updateLabel(int)));
    sbSecond->setMaximum(59);
    sbSecond->setMinimum(0);


    rbCountdown = new QRadioButton("倒计时", headGroup);
    rbCountdown->setChecked(true);
    rbCountup = new QRadioButton("正计时", headGroup);

    // 布局计时时长
    head1->addWidget(cbTimerDuration);
    head1->addWidget(sbHour);
    head1->addWidget(new QLabel("时",headGroup));
    head1->addWidget(sbMinute);
    head1->addWidget(new QLabel("分",headGroup));
    head1->addWidget(sbSecond);
    head1->addWidget(new QLabel("秒",headGroup));
    head1->addSpacing(width_size*2);
    head1->addWidget(rbCountdown);
    head1->addWidget(rbCountup);
    headLayout->addLayout(head1);

    QHBoxLayout *head2 = new QHBoxLayout();  // 不指定父对象
    // 警报设置
    cbWarning1 = new QCheckBox("报警1", headGroup);
    sbWarning1Time = new QSpinBox(headGroup);
    sbWarning1Time->setRange(0,m_timerConfig.durationMs/1000);
    sbWarning1Time->setFixedWidth(width_size_SpinBox);
    connect(sbWarning1Time, SIGNAL(valueChanged(int)), this, SLOT(updateWarn1Spin(int)));
    head2->addWidget(cbWarning1);
    head2->addSpacing(width_size);
    head2->addWidget(new QLabel("余", headGroup));
    head2->addWidget(sbWarning1Time);
    head2->addWidget(new QLabel("秒", headGroup));
    head2->addStretch(); // 添加一个弹簧
    headLayout->addLayout(head2);

    QHBoxLayout *head3 = new QHBoxLayout();  // 不指定父对象
    cbWarning2 = new QCheckBox("报警2", headGroup);
    sbWarning2Time = new QSpinBox(headGroup);
    sbWarning2Time->setRange(0,m_timerConfig.durationMs/1000);
    sbWarning2Time->setFixedWidth(width_size_SpinBox);
    connect(sbWarning2Time, SIGNAL(valueChanged(int)), this, SLOT(updateWarn2Spin(int)));

    head3->addWidget(cbWarning2);
    head3->addSpacing(width_size);
    head3->addWidget(new QLabel("余", headGroup));
    head3->addWidget(sbWarning2Time);
    head3->addWidget(new QLabel("秒", headGroup));
    head3->addStretch(); // 添加一个弹簧
    headLayout->addLayout(head3);

    QHBoxLayout *head4 = new QHBoxLayout();  // 不指定父对象
    cbWarning3 = new QCheckBox("报警3", headGroup);
    sbWarning3Time = new QSpinBox(headGroup);
    sbWarning3Time->setRange(0,m_timerConfig.durationMs/1000);
    sbWarning3Time->setFixedWidth(width_size_SpinBox);
    connect(sbWarning3Time, SIGNAL(valueChanged(int)), this, SLOT(updateWarn3Spin(int)));
    cbContinuousWarning = new QCheckBox("持续提醒", headGroup);
    head4->addWidget(cbWarning3);
    head4->addSpacing(width_size);
    head4->addWidget(new QLabel("余", headGroup));
    head4->addWidget(sbWarning3Time);
    head4->addWidget(new QLabel("秒", headGroup));
    head4->addStretch(); // 添加一个弹簧
    head4->addWidget(cbContinuousWarning);
    headLayout->addLayout(head4);

    QHBoxLayout *head5 = new QHBoxLayout();  // 不指定父对象
    // 超时设置
    cbOvertime = new QCheckBox("超时", headGroup);
    sbOvertimeDuration = new QSpinBox(headGroup);
    sbOvertimeDuration->setFixedWidth(width_size_SpinBox);
    head5->addWidget(cbOvertime);
    head5->addSpacing(width_size*1.5);
    head5->addWidget(sbOvertimeDuration);
    head5->addWidget(new QLabel("秒停止计时", headGroup));
    head5->addStretch(); // 添加一个弹簧
    headLayout->addLayout(head5);

    // headLayout在第246行创建时已经指定了headGroup为父对象，不需要再次setLayout

    // 将滚动区域添加到主布局
    mainLayout->addWidget(headGroup);

    setTimeData(m_timerConfig.durationMs);
    //格式设置
    QGroupBox *formatGroup = new QGroupBox("格式",this);
    // 移除固定高度限制
    QHBoxLayout *formatLayout = new QHBoxLayout(formatGroup);
    rbFormat59Sec = new QRadioButton("59 (秒)", formatGroup);
    rbFormat59MinSec = new QRadioButton("59:59 (分秒)", formatGroup);
    rbFormat23HoursMinSec = new QRadioButton("23:59:59 (时分秒)", formatGroup);
    setFormat();
    formatLayout->addWidget(rbFormat59Sec);
    formatLayout->addWidget(rbFormat59MinSec);
    formatLayout->addWidget(rbFormat23HoursMinSec);

    // formatLayout在第350行创建时已经指定了formatGroup为父对象，不需要再次setLayout
    mainLayout->addWidget(formatGroup);

    // 超时动作设置
    QGroupBox *overtimeGroup = new QGroupBox("超时动作",this);
    // 移除固定高度限制
    QVBoxLayout *overtimeLayout = new QVBoxLayout(overtimeGroup);
    QHBoxLayout *overtime1 = new QHBoxLayout();  // 不指定父对象
    rbOvertimeCount = new QRadioButton("超时计时", overtimeGroup);
    rbStopCount = new QRadioButton("停止计时", overtimeGroup);
    rbLoopCount = new QRadioButton("循环计时", overtimeGroup);
    overtime1->addWidget(rbOvertimeCount);
    overtime1->addWidget(rbStopCount);
    overtime1->addWidget(rbLoopCount);
    overtimeLayout->addLayout(overtime1);

    QHBoxLayout *overtime2 = new QHBoxLayout();  // 不指定父对象
    cbTransparent = new QCheckBox("屏幕半透明", overtimeGroup);
    connect(cbTransparent, &QCheckBox::stateChanged, this, &TimedWidget::onTransparentChanged);
    cbScreenBlack = new QCheckBox("屏幕黑屏", overtimeGroup);
    connect(cbScreenBlack, &QCheckBox::stateChanged, this, &TimedWidget::onScreenBlackChanged);
    cbScreenWhite = new QCheckBox("屏幕白屏", overtimeGroup);
    connect(cbScreenWhite, &QCheckBox::stateChanged, this, &TimedWidget::onScreenWhiteChanged);
    overtime2->addWidget(cbTransparent);
    overtime2->addWidget(cbScreenBlack);
    overtime2->addWidget(cbScreenWhite);
    setTimeOutAction();
    overtimeLayout->addLayout(overtime2);

    // overtimeLayout在第365行创建时已经指定了overtimeGroup为父对象，不需要再次setLayout
    mainLayout->addWidget(overtimeGroup);
    // 播放设置
    QGroupBox *playbackGroup = new QGroupBox("播放",this);
    // 移除固定高度限制
    QGridLayout *playbackLayout = new QGridLayout(playbackGroup);
    cbSmartCount = new QCheckBox("智能计时", playbackGroup);
    cbCountSettings = new QCheckBox("计时设置", playbackGroup);
    cbPauseCount = new QCheckBox("暂停计时", playbackGroup);
    cbChangeTime = new QCheckBox("不切换时间", playbackGroup);
    cbHideClock = new QCheckBox("不计时隐藏", playbackGroup);
    cbShowOnSecondaryScreen = new QCheckBox("副屏显示", playbackGroup);

    playbackLayout->addWidget(cbSmartCount, 0, 0);
    playbackLayout->addWidget(cbCountSettings, 0, 1);
    playbackLayout->addWidget(cbPauseCount, 0, 2);
    playbackLayout->addWidget(cbChangeTime, 1, 0);
    playbackLayout->addWidget(cbHideClock, 1, 1);
    playbackLayout->addWidget(cbShowOnSecondaryScreen, 1, 2);

    setPlayback();

    // playbackLayout在第393行创建时已经指定了playbackGroup为父对象，不需要再次setLayout
    mainLayout->addWidget(playbackGroup);

    // 时钟设置
    QGroupBox *clockGroup = new QGroupBox("时钟",this);
    QVBoxLayout *clockLayout = new QVBoxLayout(clockGroup);
    QHBoxLayout *clock1 = new QHBoxLayout();  // 不指定父对象
    fontCombo = new QComboBox(clockGroup);
    // 添加常用字体
    fontCombo->addItem("Arial");
    fontCombo->addItem("Times New Roman");
    fontCombo->addItem("Verdana");
    fontCombo->addItem("Helvetica");
    fontCombo->addItem("Courier New");
    fontCombo->addItem("Georgia");
    fontCombo->addItem("Tahoma");
    fontCombo->addItem("Trebuchet MS");
    fontCombo->addItem("Impact");
    fontCombo->addItem("Comic Sans MS");
    fontCombo->addItem("Lucida Console");
    fontCombo->addItem("Palatino Linotype");
    fontCombo->addItem("Segoe UI");
    fontCombo->addItem("Open Sans");
    fontCombo->addItem("Roboto");
    fontCombo->addItem("Noto Sans");
    fontCombo->addItem("Monaco");

    fontSizeCombo = new QComboBox(clockGroup);
    for(int i = 6;i<20;i+=2){
        fontSizeCombo->addItem(QString::number(i));
    }

    setFontData();

    colorCombo = new QComboBox(clockGroup);
    clock1->addWidget(new QLabel("字体", clockGroup));
    clock1->addWidget(fontCombo);
    clock1->addSpacing(width_size);
    clock1->addWidget(new QLabel("字号", clockGroup));
    clock1->addWidget(fontSizeCombo);
    clock1->addSpacing(width_size);
    clock1->addWidget(new QLabel("颜色", clockGroup));
    clock1->addWidget(colorCombo);
    clock1->addSpacing(width_size);
    clockLayout->addLayout(clock1);

    QHBoxLayout *clock2 = new QHBoxLayout();  // 不指定父对象
    cbTransparentBackground = new QCheckBox("透明背景", clockGroup);
    backgroundPath = new FileLineEdit(clockGroup);
    backgroundPath->setText(m_bgSettings.filePath);
    backgroundPath->setFileLineEditType(FileLineEdit::FileLineEditType::Image);
    radiusSpinBox = new QSpinBox(clockGroup);

    clock2->addWidget(cbTransparentBackground);
    clock2->addWidget(new QLabel("背景路径", clockGroup));
    clock2->addWidget(backgroundPath);
    clock2->addSpacing(width_size);
    clock2->addWidget(new QLabel("半径", clockGroup));
    clock2->addWidget(radiusSpinBox);
    clockLayout->addLayout(clock2);

    // clockLayout在第415行创建时已经指定了clockGroup为父对象，不需要再次setLayout
    mainLayout->addWidget(clockGroup);

    // 按钮
    QHBoxLayout *buttonLayout = new QHBoxLayout();  // 不指定父对象，避免重复设置布局
#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
    buttonLayout->setContentsMargins(10, 10, 10, 10);
#else
    buttonLayout->setMargin(10);
#endif
    btnSpecialCount = new QPushButton("特定计时", this);
    btnSpecialCount->setObjectName("btnSpecialCount");
    btnSpecialCount->setProperty("styleClass", "secondary");
    
    btnHelp = new QPushButton("帮助", this);
    btnHelp->setObjectName("btnHelp");
    btnHelp->setProperty("styleClass", "secondary");
    
    btnApply = new QPushButton("应用", this);
    btnApply->setObjectName("btnApply");
    btnApply->setProperty("styleClass", "primary");
    connect(btnApply,&QPushButton::clicked,this,&TimedWidget::onSaveDataBtn);
    
    btnClose = new QPushButton("关闭", this);
    btnClose->setObjectName("btnClose");
    btnClose->setProperty("styleClass", "secondary");
    connect(btnClose,&QPushButton::clicked,this,[this](){emit sigClose();});
    
    buttonLayout->addWidget(btnSpecialCount);
    buttonLayout->addWidget(btnHelp);
    buttonLayout->addWidget(btnApply);
    buttonLayout->addWidget(btnClose);
    mainLayout->addLayout(buttonLayout);

    setLayout(mainLayout);
}

void TimedWidget::initData()
{
    // ✅ 使用ConfigService替代直接访问AppConfig
    auto& configService = ConfigService::instance();
    
    m_font = configService.getFont();
    m_timerConfig = configService.getTimerConfig();
    m_timeoutAction = configService.getTimeoutAction();
    m_playbackSettings = configService.getPlaybackSettings();
    m_bgSettings = configService.getBackgroundSettings();
    m_timeFormat = configService.getTimeFormat();
    
    logDebug("TimedWidget 数据已初始化");
}

void TimedWidget::saveData()
{
    // ✅ 使用ConfigService替代直接访问AppConfig
    auto& configService = ConfigService::instance();
    
    // 验证配置
    QString errorMsg;
    if (!configService.validateTimerConfig(m_timerConfig, &errorMsg)) {
        logError("配置验证失败: " << errorMsg);
        QMessageBox::warning(this, "配置错误", errorMsg);
        return;
    }
    
    // 保存配置
    configService.setFont(m_font);
    configService.setTimerConfig(m_timerConfig);
    configService.setTimeoutAction(m_timeoutAction);
    configService.setPlaybackSettings(m_playbackSettings);
    configService.setBackgroundSettings(m_bgSettings);
    configService.setTimeFormat(m_timeFormat);
    
    // 保存到文件
    configService.saveConfig();
    
    logInfo("TimedWidget 配置已保存");
}

void TimedWidget::setTimeData(int time)
{
    if (!sbHour || !sbMinute || !sbSecond) {
        qWarning() << "Time spin boxes are not initialized!";
        return;
    }
    cbTimerDuration->setChecked(m_timerConfig.isTimerEnabled);
    cbWarning1->setChecked(m_timerConfig.isAlarm1Enabled);
    cbWarning2->setChecked(m_timerConfig.isAlarm2Enabled);
    cbWarning3->setChecked(m_timerConfig.isAlarm3Enabled);
    cbContinuousWarning->setChecked(m_timerConfig.isContinuousReminder);
    cbOvertime->setChecked(m_timerConfig.isTimeoutEnabled);
     if(m_timerConfig.mode == TimerMode::Countdown){
         rbCountdown->setChecked(true);
     }else{
         rbCountup->setChecked(true);
     }
    // 确保输入的时间是正数，并计算时间组件
    int totalSeconds = static_cast<int>(abs(time / 1000));
    int hours = totalSeconds / 3600;
    int minutes = (totalSeconds % 3600) / 60;
    int seconds = totalSeconds % 60;

    // 设置时间值
    sbHour->setValue(hours);
    sbMinute->setValue(minutes);
    sbSecond->setValue(seconds);

    sbWarning1Time->setRange(0,m_timerConfig.durationMs);
    sbWarning2Time->setRange(0,m_timerConfig.durationMs);
    sbWarning3Time->setRange(0,m_timerConfig.durationMs);
    sbOvertimeDuration->setRange(0,24*60*60);

    sbWarning1Time->setValue(m_timerConfig.alarm1Ms/1000);
    sbWarning2Time->setValue(m_timerConfig.alarm2Ms/1000);
    sbWarning3Time->setValue(m_timerConfig.alarm3Ms/1000);
    sbOvertimeDuration->setValue(m_timerConfig.timeoutMs/1000);
}

int TimedWidget::getTimeData()
{
    if (!sbHour || !sbMinute || !sbSecond) {
        qWarning() << "Time spin boxes are not initialized!";
        return 0;
    }
    m_timerConfig.isTimerEnabled = cbTimerDuration->isChecked();
    m_timerConfig.isAlarm1Enabled = cbWarning1->isChecked();
    m_timerConfig.isAlarm2Enabled = cbWarning2->isChecked();
    m_timerConfig.isAlarm3Enabled = cbWarning3->isChecked();
    m_timerConfig.isContinuousReminder = cbContinuousWarning->isChecked();
    m_timerConfig.isTimeoutEnabled = cbOvertime->isChecked();

    m_timerConfig.alarm1Ms = sbWarning1Time->value()*1000;
    m_timerConfig.alarm2Ms = sbWarning2Time->value()*1000;
    m_timerConfig.alarm3Ms = sbWarning3Time->value()*1000;
    m_timerConfig.timeoutMs = sbOvertimeDuration->value()*1000;

    if(rbCountdown->isChecked()){
        m_timerConfig.mode = TimerMode::Countdown;
    }

    if(rbCountup->isChecked()){
        m_timerConfig.mode = TimerMode::Stopwatch;
    }

    // 计算总时间（秒数）
    int time = sbHour->value() * 3600 + sbMinute->value() * 60 + sbSecond->value();
    return time * 1000;
}

void TimedWidget::setFontData()
{
    fontCombo->setCurrentText(m_font.family());
    fontSizeCombo->setCurrentText(QString::number(m_font.pointSize()));
}

QFont TimedWidget::getFontData()
{
    m_font.setFamily(fontCombo->currentText());

    m_font.setPointSize(fontSizeCombo->currentText().toInt());

    // 设置整个页面的字体
    setFont(m_font);

    return m_font;
}

void TimedWidget::setFormat()
{
    switch (m_timeFormat) {
    case TimeFormat::Seconds:
        rbFormat59Sec->setChecked(true);
        rbFormat59MinSec->setChecked(false);
        rbFormat23HoursMinSec->setChecked(false);
        break;
    case TimeFormat::MinuteSecond:
        rbFormat59Sec->setChecked(false);
        rbFormat59MinSec->setChecked(true);
        rbFormat23HoursMinSec->setChecked(false);
        break;
    case TimeFormat::HourMinuteSecond:
        rbFormat59Sec->setChecked(false);
        rbFormat59MinSec->setChecked(false);
        rbFormat23HoursMinSec->setChecked(true);
        break;
    default:
        return;
    }
}

void TimedWidget::getFormat()
{
    if(rbFormat59Sec->isChecked()){
        m_timeFormat = TimeFormat::Seconds;
    }

    if(rbFormat59MinSec->isChecked()){
        m_timeFormat = TimeFormat::MinuteSecond;
    }

    if(rbFormat23HoursMinSec->isChecked()){
        m_timeFormat = TimeFormat::HourMinuteSecond;
    }
}

void TimedWidget::setTimeOutAction()
{
    switch (m_timeoutAction.actionType) {
    case TimeoutActionType::TimeoutCount:
        rbOvertimeCount->setChecked(true);
        rbStopCount->setChecked(false);
        rbLoopCount->setChecked(false);
        break;
    case TimeoutActionType::StopCount:
        rbOvertimeCount->setChecked(false);
        rbStopCount->setChecked(true);
        rbLoopCount->setChecked(false);
        break;
    case TimeoutActionType::LoopCount:
        rbOvertimeCount->setChecked(false);
        rbStopCount->setChecked(false);
        rbLoopCount->setChecked(true);
        break;
    default:
        break;
    }

    switch (m_timeoutAction.screenAction) {
    case ScreenAction::SemiTransparent:
        cbTransparent->setChecked(true);
        cbScreenBlack->setChecked(false);
        cbScreenWhite->setChecked(false);
        break;
    case ScreenAction::BlackScreen:
        cbTransparent->setChecked(false);
        cbScreenBlack->setChecked(true);
        cbScreenWhite->setChecked(false);
        break;
    case ScreenAction::WhiteScreen:
        cbTransparent->setChecked(false);
        cbScreenBlack->setChecked(false);
        cbScreenWhite->setChecked(true);
        break;
    default:
        break;
    }
}

void TimedWidget::getTimeOutAction()
{
    if(rbOvertimeCount->isChecked()){
        m_timeoutAction.actionType = TimeoutActionType::TimeoutCount;
    }
    if(rbStopCount->isChecked()){
        m_timeoutAction.actionType = TimeoutActionType::StopCount;
    }
    if(rbLoopCount->isChecked()){
        m_timeoutAction.actionType = TimeoutActionType::LoopCount;
    }

    if(cbTransparent->isChecked()){
        m_timeoutAction.screenAction = ScreenAction::SemiTransparent;
    }
    if(cbScreenBlack->isChecked()){
        m_timeoutAction.screenAction = ScreenAction::BlackScreen;
    }
    if(cbScreenWhite->isChecked()){
        m_timeoutAction.screenAction = ScreenAction::WhiteScreen;
    }
}

void TimedWidget::setPlayback()
{
    cbSmartCount->setChecked(m_playbackSettings.smartTiming);
    cbCountSettings->setChecked(m_playbackSettings.timelySetting);
    cbPauseCount->setChecked(m_playbackSettings.pauseTiming);
    cbChangeTime->setChecked(m_playbackSettings.noSwitchTime);
    cbHideClock->setChecked(m_playbackSettings.hideWhenNotTiming);
    cbShowOnSecondaryScreen->setChecked(m_playbackSettings.dualScreenDisplay);
}

void TimedWidget::getPlayback()
{
    m_playbackSettings.smartTiming = cbSmartCount->isChecked();
    m_playbackSettings.timelySetting = cbCountSettings->isChecked();
    m_playbackSettings.pauseTiming = cbPauseCount->isChecked();
    m_playbackSettings.noSwitchTime = cbChangeTime->isChecked();
    m_playbackSettings.hideWhenNotTiming = cbHideClock->isChecked();
    m_playbackSettings.dualScreenDisplay = cbShowOnSecondaryScreen->isChecked();
}

void TimedWidget::onSaveDataBtn()
{
    // 收集UI数据
    m_timerConfig.durationMs = getTimeData();
    getFormat();
    getTimeOutAction();
    getPlayback();
    m_font = getFontData();
    
    // 背景路径
    if (!backgroundPath->text().isEmpty()) {
        m_bgSettings.filePath = backgroundPath->text();
    }
    
    // 保存数据（内部有验证）
    saveData();
    
    // ❌ 不再需要调用 AppConfig::getInstance().UpdatData()
    // ✅ ConfigService::saveConfig() 已经处理了
    
    // 应用新字体
    setFont(m_font);
    update();
    
    // 发出关闭信号
    emit sigClose();
    
    logInfo("用户保存了配置");
}

void TimedWidget::updateLabel(int value)
{
    // 计算总时间（秒数）
    m_timerConfig.durationMs = sbHour->value() * 3600 + sbMinute->value() * 60 + sbSecond->value();
    sbWarning1Time->setRange(0,m_timerConfig.durationMs);
    sbWarning2Time->setRange(sbWarning1Time->value()+4,m_timerConfig.durationMs);
    sbWarning3Time->setRange(sbWarning2Time->value()+4,m_timerConfig.durationMs);
}

void TimedWidget::updateWarn1Spin(int value)
{
    sbWarning2Time->setRange(value,sbWarning3Time->value());
    sbWarning3Time->setRange(sbWarning2Time->value()+4,m_timerConfig.durationMs);
}

void TimedWidget::updateWarn2Spin(int value)
{
    sbWarning1Time->setRange(0,value);
    sbWarning3Time->setRange(value,m_timerConfig.durationMs);
}

void TimedWidget::updateWarn3Spin(int value)
{

}

void TimedWidget::onTransparentChanged(int state)
{
    if (state == Qt::Checked) {
        cbScreenBlack->setChecked(false);
        cbScreenWhite->setChecked(false);
    }
}

void TimedWidget::onScreenBlackChanged(int state)
{
    if (state == Qt::Checked) {
        cbTransparent->setChecked(false);
        cbScreenWhite->setChecked(false);
    }
}

void TimedWidget::onScreenWhiteChanged(int state)
{
    if (state == Qt::Checked) {
        cbTransparent->setChecked(false);
        cbScreenBlack->setChecked(false);
    }
}
